package com.ruoyi.wxlogin.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.wxlogin.pojo.WxSystem;
import com.ruoyi.wxlogin.pojo.WxUser;
import com.ruoyi.wxlogin.weixin.WxService;
import com.ruoyi.wxlogin.weixin.WxUserInfo;
import com.ruoyi.wxcommon.common.Result;
import com.ruoyi.wxcommon.constant.RedisKey;
import com.ruoyi.wxlogin.mapper.WxUserMapper;
import com.ruoyi.wxlogin.service.IWeixinService;
import com.ruoyi.wxlogin.weixin.WXAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.wxlogin.utils.RedisM.RedisInJava;


/**
 * @author crush
 * @since 2021-09-14
 */
@Service
public class WeixinServiceImpl extends ServiceImpl<WxUserMapper, WxUser> implements IWeixinService {


    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    WxService wxService;


    @Override
    public Result getSessionId(String code) {
        Map<String,Object> map = new  HashMap<>();
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
        String res = HttpUtil.get(replaceUrl);
        if (res != null && !res.isEmpty()){
            map.put("data",res);
            String s = UUID.randomUUID().toString();
            Map<String,Object> parseObject = JSONArray.parseObject(res);
            WxSystem wxSystem = WxSystem.builder().token(parseObject.get("session_key").toString()).openId(parseObject.get("openid").toString()).build();
            map.put("sessionId",s);
            redisTemplate.opsForValue().set(RedisKey.WX_USER + wxSystem.getOpenId() + RedisKey.OPENID, res,7, TimeUnit.DAYS);
            return Result.SUCCESS(wxSystem);
        }
        return Result.FAIL("用户异常");
    }
    @Override
    public Result userInfo(String openId) {
        String result = redisTemplate.opsForValue().get(RedisKey.WX_USER + openId + RedisKey.USERINFO);
        if (result != null){
            WxUser user = RedisInJava(redisTemplate.opsForValue().get(RedisKey.WX_USER + openId + RedisKey.USERINFO), WxUser.class);
            return Result.SUCCESS(user);
        }
        return Result.FAIL("请先登录");
    }
    @Override
    public Result authLogin(WXAuth wxAuth) {
        try {
            String wxRes = wxService.wxDecrypt(wxAuth.getEncryptedData(), wxAuth.getSessionId(), wxAuth.getIv());

            WxUserInfo wxUserInfo = JSON.parseObject(wxRes,WxUserInfo.class);
            // 业务操作：你可以在这里利用数据 对数据库进行查询， 如果数据库中没有这个数据，就添加进去，即实现微信账号注册

            // 如果是已经注册过的，就利用数据，生成jwt 返回token，实现登录状态
            return Result.SUCCESS(wxUserInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.FAIL();
    }


}
